package com.wutong.erb.config.security;

import com.wutong.erb.config.CorsConfig;
import com.wutong.erb.filter.BusinessJwtAuthenticationFilter;
import com.wutong.erb.filter.PageAddTokenFilter;
import com.wutong.erb.filter.RateLimitFilter;
import com.wutong.erb.filter.RegisterJwtAuthenticationFilter;
import com.wutong.erb.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import static com.wutong.erb.filter.RegisterJwtAuthenticationFilter.REGISTER_WHITE_LIST;

/**
 * 安全配置，禁用CSRF，开启无状态会话
 *
 * @author wutong
 */
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

    private final CorsConfig corsConfig;
    private final RedisTemplate<String, String> redisTemplate;

    private final UserMapper userMapper;

    /**
     * 页面访问配置
     * @param http HTTP 安全性
     * @return 安全过滤器链
     * @throws Exception 异常
     */
    @Bean
    public SecurityFilterChain pageSecurityFilterChain(HttpSecurity http) throws Exception {
        http.securityMatcher("/page/**")
                .cors(cors -> cors.configurationSource(corsConfig.corsConfigurationSource()))
                .csrf(CsrfConfigurer::disable)
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                ).authorizeHttpRequests(auth -> auth
                        .anyRequest().permitAll()
                ).addFilterBefore(
                        new RateLimitFilter(),
                        UsernamePasswordAuthenticationFilter.class
                ).addFilterBefore(
                        new PageAddTokenFilter(redisTemplate),
                        UsernamePasswordAuthenticationFilter.class
                );
        return http.build();
    }

    /**
     * 用户验证配置
     * @param http HTTP 安全性
     * @return 安全过滤器链
     * @throws Exception 异常
     */
    @Bean
    public SecurityFilterChain userRegisterAuthSecurityFilterChain(HttpSecurity http) throws Exception {
        http.securityMatcher("/api/auth/**")
                .cors(cors -> cors.configurationSource(corsConfig.corsConfigurationSource()))
                .csrf(CsrfConfigurer::disable)
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                ).authorizeHttpRequests(auth -> auth
                        .requestMatchers(
                                REGISTER_WHITE_LIST
                        ).permitAll()
                        .anyRequest().authenticated()
                ).addFilterBefore(
                        new RegisterJwtAuthenticationFilter(redisTemplate),
                        UsernamePasswordAuthenticationFilter.class
                );
        return http.build();
    }

    /**
     * 业务接口配置
     * @param http HTTP 安全性
     * @return 安全过滤器链
     * @throws Exception 异常
     */
    @Bean
    public SecurityFilterChain businessAuthSecurityFilterChain(HttpSecurity http) throws Exception {
        http.securityMatcher("/api/user/**")
                .cors(cors -> cors.configurationSource(corsConfig.corsConfigurationSource()))
                .csrf(CsrfConfigurer::disable)
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                ).authorizeHttpRequests(auth -> auth
                        .anyRequest().authenticated()
                ).addFilterBefore(
                        new RateLimitFilter(),
                        UsernamePasswordAuthenticationFilter.class
                ).addFilterBefore(
                        new BusinessJwtAuthenticationFilter(userMapper, redisTemplate),
                        UsernamePasswordAuthenticationFilter.class
                );
        return http.build();
    }

}

